#pragma once 

#include <iostream>
#include <string>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#define BUF_NUM 1024

namespace tcpc
{
    class TcpClient
    {
    public:
        TcpClient(const std::string &serverip, const uint16_t &serverport)
        :_sock(-1), _serverip(serverip), _serverport(serverport)
        {}
        void initTcpClient()
        {
            //step 1:创建客户端自身的套接字
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if(_sock < 0)
            {
                std::cout << "socket create error" << std::endl;
                exit(1);
            }
            std::cout << "socket create success" << std::endl;
            //不需要显示的bind，让 OS 自动帮我们去选择相应的ip和接口
        }
        void runTcpClient()
        {
            struct sockaddr_in server;
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            server.sin_port = htons(_serverport);
            //step 2:将客户端的套接字与服务端套接字进行链接
            if(connect(_sock, (struct sockaddr*)&server, sizeof(server)) != 0)
            {
                std::cout << "socket connect error" << std::endl;
                exit(2);
            }
            else
            {
                std::cout << "socket connect success" << std::endl;
                std::string msg;
                while(true)
                {   
                    std::cout << "Please Enter# ";
                    std::getline(std::cin, msg);
                    write(_sock, msg.c_str(), msg.size());
                    char buffer[BUF_NUM];
                    int n = read(_sock, buffer, sizeof(buffer)-1);
                    if(n > 0)
                    {
                        buffer[n] = 0;
                        std::cout << "服务器回应# " << buffer << std::endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        ~TcpClient()
        {
            close(_sock);
        }
    private:
        std::string _serverip;
        uint16_t _serverport;
        int _sock;//客户端套接字，用于与服务端进行链接
    };
}